package com.alquimia.identityaccess.rest.controller;

import com.alquimia.identityaccess.application.events.user.AuthenticateUserEvent;
import com.alquimia.identityaccess.application.events.user.UpdateEmailAddressEvent;
import com.alquimia.identityaccess.application.events.user.UserAuthenticatedEvent;
import com.alquimia.identityaccess.application.events.user.UserEmailAddressUpdatedEvent;
import com.alquimia.identityaccess.application.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * Created by Ivo on 17/07/2014.
 */
@Controller
@RequestMapping("/signin")
public class AuthenticateUserCommandController {

    private static Logger LOG = LoggerFactory.getLogger(RegisterUserCommandController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<UserAuthenticatedEvent> authenticateUser(@RequestBody AuthenticateUserEvent aAuthenticateUserEvent, UriComponentsBuilder builder) {

        UserAuthenticatedEvent userAuthenticatedEvent = userService.authenticateUser(aAuthenticateUserEvent);

        if (!userAuthenticatedEvent.isEntityFound())
            return new ResponseEntity<UserAuthenticatedEvent>(userAuthenticatedEvent, HttpStatus.FORBIDDEN);


        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(
                builder.path("/users/{userId}")
                        .buildAndExpand(userAuthenticatedEvent.getUserId()).toUri()
        );

        return new ResponseEntity<UserAuthenticatedEvent>(userAuthenticatedEvent, headers, HttpStatus.OK);
    }
}
